const express = require('express');
const router = express.Router();
const md5 = require('md5');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const redisClient = require('../config/redis');


router.post('/login', async (req, res) => {
    const { userName, password, code } = req.body;

    try {
        // 校验验证码
        if (req.session.captchaResult !== code) {
            return res.status(400).json({ msg: '验证码错误' });
        }
        // 查找用户
        let user = await User.findOne({ userName })
            .populate({
                path: 'roles',
                populate: {
                    path: 'permissions'
                }
            });
        if (!user) {
            return res.status(400).json({ message: '用户名或密码错误' });
        }

        // 验证密码 (使用存储在用户文档中的盐值)
        const hashedPassword = md5(password + process.env.SALT);
        if (hashedPassword !== user.password) {
            return res.status(400).json({ message: '用户名或密码错误' });
        }

        // 生成 JWT token (使用环境变量配置过期时间)
        const payload = { userId: user._id, roles: user.roles.map(role => role.code) };
        const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN * 1000 });

        // 将用户信息和 token 存储到 Redis 缓存中
        await redisClient.set(`user:${user._id}`, JSON.stringify(user), 'EX', process.env.JWT_EXPIRES_IN);

        res.json({ message: '登录成功', token, user });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '登录失败' });
    }
});

module.exports = router;